package com.bestom.waterquality;

import android.annotation.SuppressLint;
import android.app.Application;
import android.graphics.Rect;
import android.os.Build;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.View;

import androidx.annotation.RequiresApi;

import com.bestom.waterquality.entity.Constant;
import com.bestom.waterquality.sql.DbHelper;
import com.bestom.waterquality.sql.DbManage;
import com.bestom.waterquality.util.SharedPreferencesUtil;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;

import cn.wch.ch934xlib.CH934XManager;

public class WaterQualityApplication extends Application {

    private static WaterQualityApplication application;
    private String devicesId;

    /** mtIsOk  mt2IsOk 用于判断 MQTT 是否连接*/
    public static boolean mtIsOk = false;
    public static boolean mt2IsOk = false;

    @Override
    public void onCreate() {
        super.onCreate();
        application = this;
        devicesId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
        // SharedPreferences初始化
        SharedPreferencesUtil.init(this);
        // CH934X初始化
        CH934XManager.getInstance().init(this);
        // 获取当天三类传感器值的平均值
        ORPAvg = (Float) SharedPreferencesUtil.getInstance().getValue(Constant.ORPAvg, 0.0);
        PHAvg = (Float) SharedPreferencesUtil.getInstance().getValue(Constant.PHAvg, 0.0);
        VCPAvg = (Float) SharedPreferencesUtil.getInstance().getValue(Constant.VCPAvg, 0.0);
        // 开启定时，每天 23:59:59 或 23:59:58 或 23:59:57 做一次数据库的更新
        mHandler.postDelayed(mRunnable,3000);
    }

    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler();

    private String getCurrentHourMinute() {
        Calendar cal = Calendar.getInstance();

        int mYear = cal.get(Calendar.YEAR);//年
        int mMonth = cal.get(Calendar.MONTH) + 1;//月
        int mDay = cal.get(Calendar.DAY_OF_MONTH);//日
        int mHour = cal.get(Calendar.HOUR_OF_DAY);//24小时格式    HOUR(12小时格式)
        int mMinute = cal.get(Calendar.MINUTE);//分
        int mSecond = cal.get(Calendar.SECOND);//秒

        return mYear + "-" + mMonth + "-" + mDay + " " + mHour + ":" + mMinute + ":" + mSecond;
    }

    private final Runnable mRunnable = new Runnable() {
        @RequiresApi(api = Build.VERSION_CODES.O)
        @Override
        public void run() {
            String time = getCurrentHourMinute();
            String[] split = time.split(" ");
            if (split[1].equals("23:59:59") || split[1].equals("23:59:58") || split[1].equals("23:59:57")){
                String data = DbManage.getInstance(getApplicationContext()).selectTodayAvg(DbHelper.ORP_Record_NAME, "data", split[0]);
                String data1 = DbManage.getInstance(getApplicationContext()).selectTodayAvg(DbHelper.PH_Record_NAME, "data", split[0]);
                String data2 = DbManage.getInstance(getApplicationContext()).selectTodayAvg(DbHelper.VCP_Record_NAME, "data", split[0]);

                DbManage.getInstance(getApplicationContext()).addAvg(DbHelper.ORP_NAME, time, data);
                DbManage.getInstance(getApplicationContext()).addAvg(DbHelper.PH_NAME, time, data1);
                DbManage.getInstance(getApplicationContext()).addAvg(DbHelper.VCP_NAME, time, data2);

                // 定时更新平均值数据
                DbManage.getInstance(getApplicationContext()).updateAvg();

                //定时删除七天前的数据
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String beforeDate = "";
                try {
                    Date date = dateFormat.parse(split[0]);
                    Date newDate = new Date(date.getTime() - 604800000L);
                    beforeDate = dateFormat.format(newDate);
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                DbManage.getInstance(getApplicationContext()).deleteDataAndImage(beforeDate);
                Log.d("mRunnable", "定时更新平均值数据,删除七天前的数据，时间--->" + time);
            }
            mHandler.postDelayed(this,3000);
        }
    };

    public static synchronized WaterQualityApplication getApplication() {
        return application;
    }

    public String getDevicesId() {
        return devicesId;
    }

    private Float ORPAvg;
    private Float PHAvg;
    private Float VCPAvg;

    public Float getORPAvg(){
        return ORPAvg;
    }

    public Float getPHAvg(){
        return PHAvg;
    }

    public Float getVCPAvg(){
        return VCPAvg;
    }

    /**
     * @param root
     * 最外层布局，需要调整的布局
     * @param scrollToView
     * 被键盘遮挡的scrollToView，滚动root,使scrollToView在root可视区域的底部
     */
    public void controlKeyboardLayout(final View root, final View scrollToView) {
        // 注册一个回调函数，当在一个视图树中全局布局发生改变或者视图树中的某个视图的可视状态发生改变时调用这个回调函数。
        root.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
            Rect rect = new Rect();
            // 获取root在窗体的可视区域
            root.getWindowVisibleDisplayFrame(rect);
            // 当前视图最外层的高度减去现在所看到的视图的最底部的y坐标
            int rootInvisibleHeight = root.getRootView()
                    .getHeight() - rect.bottom;

            // 若rootInvisibleHeight高度大于100，则说明当前视图上移了，说明软键盘弹出了
            if (rootInvisibleHeight > 100) {
                //软键盘弹出来的时候
                int[] location = new int[2];
                // 获取scrollToView在窗体的坐标
                scrollToView.getLocationInWindow(location);
                // 计算root滚动高度，使scrollToView在可见区域的底部
                int srollHeight = (location[1] + scrollToView
                        .getHeight()) - rect.bottom;
                root.scrollTo(0, srollHeight);
            } else {
                // 软键盘没有弹出来的时候
                root.scrollTo(0, 0);
            }
        });
    }
}